package club.menglinking.wechat.configuration;

import club.menglinking.wechat.entity.TokenEntity;
import club.menglinking.wechat.util.BaseUtil;
import club.menglinking.wechat.util.TokenContainer;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.io.IOException;

/**
 * @ClassName TokenApplicationRunner
 * @Author Administrator
 * @Date 2018/12/31 16:03
 * @Version 1.0
 * @Description 项目启动执行获取token
 **/
@Component
@Slf4j
public class TokenApplicationRunner {


    @Value("${appid}")
    private String appid;

    @Value("${appsecret}")
    private String appsecret;

    @Autowired
    private MailConfiguration mail;

    private int i = 1;

    @Scheduled(initialDelay = 1000, fixedDelay = 7000 * 1000)
    public void getAccessToken() throws IOException, MessagingException {
        log.info("-----------开始获取token------------");
        try {
            String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
            String msg = BaseUtil.getBaseUtil().getToken("GET", URL);
            ObjectMapper mapper = new ObjectMapper();
            TokenEntity entity = mapper.readValue(msg, TokenEntity.class);
            TokenContainer.getTokenContainer().getToken().put("access_token", entity.getAccess_token());
            TokenContainer.getTokenContainer().getToken().put("expires_in", entity.getExpires_in());
            log.info("---------token获取成功--------------" + TokenContainer.getTokenContainer().getToken().get("access_token"));
        } catch (Exception e) {
            log.error("第" + i + "次获取微信access_token异常");
            i++;
            if (i >= 4) {
                log.error("重试获取次数限制,发送异常报告邮件");
                i = 1;
                boolean isSend = mail.sendMail();
                if (isSend) {
                    log.debug("email send success");
                } else {
                    log.debug("email send fail");
                }
            } else {
                getAccessToken();
            }
        }
    }
}
